﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Kay.Nuget.Helper
{
    public partial class SpecEditor : Form
    {
        private string _spec;

        private package _xmlSpec;

        public SpecEditor()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化说明编辑器
        /// </summary>
        /// <param name="spec">说明文件路径</param>
        public SpecEditor(string spec) : this()
        {
            _spec = spec;
        }

        private void SpecEditor_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_spec) || _spec.Trim() == string.Empty)
            {
                MessageBox.Show(@"说明文件不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Close();
            }
            using (var sr = new StreamReader(_spec, Encoding.UTF8))
            {
                var temp = sr.ReadToEnd();
                _xmlSpec = SerializeHelper.XmlDeserizlize<package>(temp);
                sr.Close();
            }
            textBox_LicenseUrl.Text = _xmlSpec.metadata.licenseUrl;
            textBox_ProjectUrl.Text = _xmlSpec.metadata.projectUrl;
            textBox_IconUrl.Text = _xmlSpec.metadata.iconUrl;
            checkBox_Require.Checked = _xmlSpec.metadata.requireLicenseAcceptance;
            textBox_ReleaseNotes.Text = _xmlSpec.metadata.releaseNotes;
            textBox_Copyright.Text = _xmlSpec.metadata.copyright;
            textBox_Tags.Text = _xmlSpec.metadata.tags;
        }

        private void button_Save_Click(object sender, EventArgs e)
        {
            _xmlSpec.metadata.licenseUrl = textBox_LicenseUrl.Text;
            _xmlSpec.metadata.projectUrl = textBox_ProjectUrl.Text;
            _xmlSpec.metadata.iconUrl = textBox_IconUrl.Text;
            _xmlSpec.metadata.requireLicenseAcceptance = checkBox_Require.Checked;
            _xmlSpec.metadata.releaseNotes = textBox_ReleaseNotes.Text;
            _xmlSpec.metadata.copyright = textBox_Copyright.Text;
            _xmlSpec.metadata.tags = textBox_Tags.Text;
            var temp = SerializeHelper.XmlSerialize(_xmlSpec);
            var xml = new XmlDocument();
            xml.LoadXml(temp);
            xml.Save(_spec);
        }

        private void button_Save_Close_Click(object sender, EventArgs e)
        {
            button_Save.PerformClick();
            DialogResult = DialogResult.OK;
            Close();
        }

        private void button_Close_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
